"""
设备模型
"""

from model.deviceModel import insert_dev, insert_dev_param, insert_dev_statistics_info, \
        update_dev, update_dev_param, update_dev_statistics_info, search_dev, \
        delete_dev, delete_dev_param, delete_dev_statistics_info, insert_contract_link_dev, \
        insert_swinery_link_dev


class device_param(object):

        def __init__(self):
                self.id = 0
                self.device_id = 0          # 设备id ForeignKey('dev.id')
                self.wat_break = False      # 断水报警 tinyint(1)
                self.wat_flow_lo = False    # 水瞬时流量低报警 tinyint(1)
                self.wat_flow_hi = False    # 水瞬时流量高报警 tinyint(1)
                self.moto_temp_hi = False   # 电机过热状态 tinyint(1)
                self.feeder_empt = False    # 空仓报警 tinyint(1)
                self.ultr_sens_dis = False  # 超声波传感器未连接 tinyint(1)
                self.flow_sens_dis = False  # 流量传感器未连接 tinyint(1)
                self.str_line_dis = False   # 撞杆线未连接 tinyint(1)
                self.wat_val_dis = False    # 水阀线未连接 tinyint(1)
                self.online_stat = False    # 在线状态（服务端检测） tinyint(1)
                self.act_stat = False       # 激活状态 tinyint(1)
                self.duetime_prom = 0     # 有效期提醒(天) int(11)
                self.vacant_time = 0.0    # 空槽时长（分钟） float
                self.trig_num = 0.0       # 触发圈数 float
                self.trig_interval = 0.0  # 触发间隔（分钟）float
                self.cali_quan = 0.0      # 校准料量(kg)float
                self.wat_fer_rate = 0.0   # 水料比 float
                self.feed_line_ctrl = False         # 料线控制状态 tinyint(1)
                self.weight_per_circ = 0.0          # 单圈料重(kg) float
                self.vib_stat = False       # 振荡器状态（开启或停止） tinyint(1)
                self.vib_amp = 0.0          # 振动器振幅 float
                self.pow_par = False        # 0:粉料/1:颗粒料 tinyint(1)

        def create_a_device(self, deviceSN, cpuid):
                i1 = insert_dev(deviceSN=deviceSN, cpuid=cpuid, status='A')
                device_id = search_dev(deviceSN=deviceSN)[0]['id']
                i2 = insert_dev_param(device_id=device_id)
                if i1 and i2:
                        print('成功创建一台设备！')
                else:
                        print('新设备创建失败！')

        def change_dev_stat(self, deviceSN, status):
                pass

        def get_dev_stat(self, deviceSN):
                search_dev(deviceSN=deviceSN)


# 根据deviceSN获取设备id
def get_deviceID(deviceSN):
        dev = search_dev(deviceSN=deviceSN)
        if not dev:
                print('警告：该设备号不存在！')
                return False
        if len(dev) > 1:
                print('警告：检测到该设备号对应多个设备!')
                return False

        ID = dev[0]['id']
        return ID


# 判断该设备是否为对应status
# status支持传入str或列表
def judge_a_device(device_id, status):
        dev_info = search_dev(device_id=device_id)

        if not dev_info:
                return False

        dev_status = dev_info[0]['status']
        if isinstance(status, (str)):
                if status == dev_status:
                        return True
        elif isinstance(status, (list, tuple)):
                for i in status:
                        if i == dev_status:
                                return True
        else:
                print('j_a_d错误')
                return False


# 设备开机：开机自动初始化为A
def boot_a_machine(deviceSN, cpuid):
        success1 = insert_dev(deviceSN=deviceSN, cpuid=cpuid, status='A')
        device_id = get_deviceID(deviceSN)
        success2 = insert_dev_param(device_id=device_id)
        success3 = insert_dev_statistics_info(device_id=device_id)
        if success1 and success2 and success3:
                print('设备开机成功！')
        else:
                print('设备开机失败！')
                # 删表
                delete_dev(device_id=device_id)
                delete_dev_param(device_id=device_id)
                delete_dev_statistics_info(device_id=device_id)


# 设备初始化：返修(EA)售出(C)-->初始化(A)
def init_a_machine(device_id):
        # 三表清零
        bingo = judge_a_device(device_id=device_id, status=['EA', 'C'])
        if bingo:
                success1 = update_dev(device_id=device_id, status='A')     # <<<<<<<<<<<<生产时间怎么办
                success2 = update_dev_param(device_id=device_id, clean_all_old=True)
                success3 = update_dev_statistics_info(device_id=device_id, clean_all_old=True)
                if success1 and success2 and success3:
                        print('设备初始化成功！')

                else:
                        print('设备初始化失败: 数据库修改失败！')
                        print('<<<<<<<<<需要回滚')
                        # 回滚
                        # update_dev(device_id=device_id, status='A')

                        # <<<<<<<<<<<<< ？？？？？两个已经清零的表怎么办
                        # <<<<<<<<<<<<< ？？？？？
        else:
                print('设备初始化失败:需要C,EA类设备！')


# 设备打标：初始化(A)打标-->代售(B)
def label_a_machine(device_id, deviceSN):
        bingo = judge_a_device(device_id=device_id, status='A') # <<<<<<<<<<<<EB不该回B,应该回A
        if bingo:
                update_dev(device_id=device_id, deviceSN=deviceSN)
                print('设备', device_id, '打标成功！')
        else:
                print('打标失败：需要A类设备')


# 售出设备：购买待售(B)签订合同售出(C)，或返厂待售(B)不签合同售出(C)
def sell_a_machine(device_id, contract_id, whobuythis=None):
        bingo = judge_a_device(device_id=device_id, status=['B'])
        if bingo:
                success = insert_contract_link_dev(contract_id=contract_id, device_id=device_id, addname=whobuythis)

                if success:
                        update_dev(device_id=device_id, status='C')

                        print('设备售出成功！')
                else:
                        print('设备售出失败:合同添加失败！')
        else:
                print('设备售出失败：需要B类设备！')


# 绑定设备：售出(C)-->绑定(D)成功默认开启(D1)，否则回到售出(C)状态
def bind_a_machine(device_id, swinery_id):
        bingo = judge_a_device(device_id=device_id, status='C')
        if bingo:
                success1 = 11   # mqtt开机
                success2 = insert_swinery_link_dev(swinery_id=swinery_id, device_id=device_id)
                if success1 and success2:
                        update_dev(device_id=device_id, status='D1')    # <<<<<<<<<<<<<<没有用到D状态
                        print('设备绑定成功：自动开机!')
                else:
                        print('<<<<<<回滚')
                        # <<<<<<<<<<<关机
                        # <<<<<<<<<<<<猪栏设备删除
        else:
                print('设备绑定失败：需要C类设备')


# 启动设备：暂停(D2)-->启动(D1)
def turnON_a_machine(device_id):        # <<<<<<<<<<<<<<<<<<<<<<<<<设备在启用暂停时需要验证合同期限
        bingo = judge_a_device(device_id=device_id, status='D2')
        if bingo:
                success1 = 11   # mqtt开机
                if success1:
                        update_dev(device_id=device_id, status='D1')
                        print('设备启用')
                else:
                        print('mqtt错误')
        else:
                print('设备启用失败：需要D2类设备')


# 暂停设备：启动(D1)->暂停(D2)
def turnOFF_a_machine(device_id):
        bingo = judge_a_device(device_id=device_id, status='D1')
        if bingo:
                success1 = 11   # mqtt关机
                if success1:
                        update_dev(device_id=device_id, status='D2')
                        print('设备关闭')
                else:
                        print('mqtt错误')
        else:
                print('设备关闭失败：需要D1类设备')



# 禁用设备
# 返修
# 返售

# <<<<<<<<<<<<<Rf 5.20

